package com.bs.bookshare.controller;

import com.bs.bookshare.Mapper.UserMapper;
import com.bs.bookshare.common.Resp;
import com.bs.bookshare.pojo.User;
import com.bs.bookshare.request.requestDead;
import com.bs.bookshare.request.requestUser;
import com.bs.bookshare.request.requestUpdateusername;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAction {

    @Autowired
    private UserMapper userMapper;

    //登陆操作
    @PostMapping("/Login")
    public Resp userLogin(@RequestBody requestUser user) {
        User loginuser =  userMapper.getUserByid(user.getId());
        if(loginuser != null) {
            if(loginuser.getPassword().equals(user.getPwd())) {
                return Resp.ok().data("info",loginuser);
            }
        }
        return Resp.notok().data("info","LoginFailed");
    }

    //注册操作
    @PostMapping("/Register")
    @Transactional(rollbackFor = Exception.class) // 确保异常发生时回滚
    public Resp Register(@RequestBody requestUser user) {

        try {
            int row = userMapper.Register(user.getId(), user.getPwd());
            if (row > 0) {
                return Resp.ok().data("info", "success");
            } else {
                // 处理数据库操作没有影响任何行的情况
                return Resp.notok().data("info", "注册失败，未知错误");
            }
        } catch (DuplicateKeyException e) {
            // 处理主键冲突异常
            return Resp.notok().data("info", "exists");
        } catch (Exception e) {
            // 处理其他所有异常
            return Resp.notok().data("info", "注册失败，服务器错误：" + e.getMessage());
        }
    }


    //更新用户名称
    @PostMapping("/updateUsername")
    public Resp updateUsername(@RequestBody requestUpdateusername user) {
        userMapper.updateUsername(user.getUserid(),user.getUsername());
        return Resp.ok().data("info","UpdateSuccess");
    }

    //用户注销操作
    @PostMapping("/dead")
    public Resp updateUsername(@RequestBody requestDead user) {
        userMapper.deleteUser(user.getUserid());
        System.out.println(user.getUserid());
        return Resp.ok().data("info","DeleteSuccess");
    }

    @PostMapping("/getUserNumber")
    public Resp getUserNumber() {
        int usernumber = userMapper.getUserNumber();
        return Resp.ok().data("info",usernumber);
    }

}
